//
//  EnterViewController.m
//  Interventix
//
//  Created by Diego on 14/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "EnterViewController.h"
#import "CommonCrypto/CommonCryptor.h"
#import "NSData+AESCrypt.h"
#import "NSString+AESCrypt.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "NSData+Conversion.h"
#import "Define.h"
#import "ComunicationsUtils.h"
#import "SBJson.h"
#import "CryptoCR2.h"
#import "JsonCR2.h"
#import "EnterViewController.h"
#import "TabBarController.h"
#import "Syncronize.h"
#import "Intervento.h"
#import "Util.h"
#import "Buffer.h"
#import "OpenInterventoViewController.h"
#import "Cliente.h"
#import "CoreDataManager.h"
#import "DateUtil.h"
#import "SettingUtils.h"
#import "OptionUserViewController.h"

@implementation EnterViewController

@synthesize nominativo,user,login,clienti,table, myIntervents, bufferIntevents;

long long t1;
#pragma mark - Event

-(void) viewWillAppear:(BOOL)animated{
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:INTERVENT_IN_USE];
}

- (void)viewDidAppear:(BOOL)animated{
    [self syncro];
    [Util unlockBuffer];
}
- (void)viewDidLoad{
    [super viewDidLoad];
    self.dateUpdate = 0;
    self.coreDataManager = [[CoreDataManager alloc] initWhidIdUserLogged:self.user.idutente];
    
    
    /// START BUFFER
    Buffer *buffer = [[Buffer alloc] init];
    [buffer startBuffer:self.coreDataManager andUser:self.user];
    [Util unlockBuffer];
    
    
    // OSSERVATORE BUFFER
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAll) name:@"refreshBuffer" object:nil];
    
    // OSSERVATORE REFRESHSYNCRO
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(syncro_int) name:@"refreshSyncro" object:nil];
}
- (void)viewDidUnload{
    [super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

#pragma mark - Button
-(IBAction) indietro{
    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Logout"
                                                          message: [NSString stringWithFormat:@"Uscire da Interventix di %@ %@",self.user.nome,self.user.cognome]
                                                         delegate:self cancelButtonTitle:@"Annulla" otherButtonTitles:@"Esci", nil];
    [myAlertView setAlertViewStyle:UIAlertViewStyleDefault];
    [myAlertView show];
}
-(IBAction) addIntervento{
    InterventoCD *inter = [NSEntityDescription insertNewObjectForEntityForName: @"InterventoCD"
                                               inManagedObjectContext:self.coreDataManager.managedObjectContext];
    inter.idintervento = inter.numero = [Util getNextInterventoId];
    inter.buffer = @1;
    inter.cestinato = @0;
    inter.cancellato = @0;
    inter.revisione = @-1;
    inter.tecnico = [self.coreDataManager findUtente:self.user.idutente];
    inter.dataora = [[NSDate alloc] init];
    inter.user = self.user.idutente;
    
    OpenInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"OpenInterventoViewController"];
    open.intervento = inter;
    open.user = self.user;
    open.coreDataManager = self.coreDataManager;
    open.hashInter = [CoreDataManager hashcodeIntervento:inter];
    open.hashInter=0;
    
    [self.navigationController pushViewController:open animated:TRUE];

}

-(IBAction) update{
    s=0;
    self.dateUpdate = 0;
    [self syncro];
}

-(IBAction) option{
    OptionUserViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"OptionUserViewController"];
    open.coreDataManager = self.coreDataManager;
    open.user = self.user;
    [self.navigationController pushViewController:open animated:TRUE];
}

-(IBAction) order{
    /*NSString *order = [[NSUserDefaults standardUserDefaults]objectForKey:INTERVENTS_ORDER_BY_DATA];
     
     if(order != nil){
     if([order isEqualToString:@"ASC"]){
     //Order data asc
     [[NSUserDefaults standardUserDefaults] setObject:@"DESC" forKey:INTERVENTS_ORDER_BY_DATA];
     [self.order_btn.imageView setImage:[UIImage imageNamed:@"order_down.png"]];
     }
     
     if([order isEqualToString:@"DESC"]){
     //Order data DESC
     [[NSUserDefaults standardUserDefaults] setObject:@"ASC" forKey:INTERVENTS_ORDER_BY_DATA];
     [self.order_btn.imageView setImage:[UIImage imageNamed:@"order_up.png"]];
     }
     }else{
     //Order data asc
     [[NSUserDefaults standardUserDefaults] setObject:@"DESC" forKey:INTERVENTS_ORDER_BY_DATA];
     //self.order_btn.imageView.image = [UIImage imageNamed:@"order_down.png"];
     }
     [self refreshAll];*/
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVE_USER];
        [SettingUtils set:SAVE_REVISION_USERS obj:@0 user:[self.user.idutente stringValue]];
        [SettingUtils set:SAVE_REVISION_INTERVENTS obj:@0 user:[self.user.idutente stringValue]];
        [SettingUtils set:SAVE_REVISION_CLIENTS obj:@0 user:[self.user.idutente stringValue]];
        [SettingUtils set:BUFFER_INTERVENTS obj:@0 user:[self.user.idutente stringValue]];
        [[self navigationController] popViewControllerAnimated:YES];
    }
}


#pragma mark - Syncro & Refresh
-(void) syncro{
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    long long now = [[NSNumber numberWithDouble: timeStamp] doubleValue] * 1000;
    if(self.dateUpdate < (now - (1000*60*5))){
        [self syncro_int];
        self.dateUpdate = now;
    }
    [self refreshAll];
}

-(void) syncro_int{
    s=0;
    [self syncroClientAsync];
    [self syncroUserAsync];
    //[self syncroIntervetsAsync];
    
}
-(void) syncroClientAsync{
    // Syncro clienti
    NSMutableDictionary *diz2 = [[NSMutableDictionary alloc]initWithCapacity:0];
    NSString *revApp = (NSString*)[SettingUtils get:SAVE_REVISION_CLIENTS user:[user.idutente stringValue]];
    if(revApp == nil){revApp = @"0";}
    [diz2 setObject:[NSNumber numberWithInt:[revApp intValue]]forKey:@"revision"];
    
    NSString *cont_client = [SettingUtils get:CONTINUE_CLIENTS user:[user.idutente stringValue]];
    if(cont_client != nil){
        [diz2 setObject:cont_client forKey:@"continue"];
    }
    
    
    NSString * json_req2 = [JsonCR2 createRequest:@"clients" action:@"syncro" paramters:diz2 iduser:user.idutente];
    ASIFormDataRequest * request2 = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:[ComunicationsUtils getUrl]]];
    [request2 setDelegate:self];
    [request2 setTimeOutSeconds:30];
    [request2 setPostValue:json_req2 forKey:@"DATA"];
    [request2 startAsynchronous];
    
}
-(void) syncroUserAsync{
    // Syncro Utenti
    NSMutableDictionary *diz2 = [[NSMutableDictionary alloc]initWithCapacity:0];
    NSString *revApp = (NSString*)[SettingUtils get:SAVE_REVISION_USERS user:[user.idutente stringValue]];
    
    if(revApp == nil){revApp = @"0";}
    [diz2 setObject:[NSNumber numberWithInt:[revApp intValue]] forKey:@"revision"];
    
    NSString *cont_user = [SettingUtils get:CONTINUE_USERS user:[user.idutente stringValue]];
    if(cont_user != nil){
        [diz2 setObject:cont_user forKey:@"continue"];
    }
    
    NSString * json_req2 = [JsonCR2 createRequest:@"users" action:@"syncro" paramters:diz2 iduser:user.idutente];
    ASIFormDataRequest * request2 = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:[ComunicationsUtils getUrl]]];
    [request2 setDelegate:self];
    [request2 setPostValue:json_req2 forKey:@"DATA"];
    [request2 startAsynchronous];
}
-(void) syncroIntervetsAsync{
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    t1 = [[NSNumber numberWithDouble: timeStamp] doubleValue] * 1000;
    
    // Syncro Interventi
    NSMutableDictionary *diz3 = [[NSMutableDictionary alloc]initWithCapacity:0];
    NSString *revInterApp = (NSString*)[SettingUtils get:SAVE_REVISION_INTERVENTS user:[user.idutente stringValue]];
    if(revInterApp == nil){revInterApp = @"0";}
    //NSMutableArray *exclude = [[NSMutableArray alloc]initWithCapacity:0];
    //[exclude addObject:@"tecnico"];
    
    //[diz3 setObject:exclude forKey:@"exclude"];
    [diz3 setObject:[NSNumber numberWithInt:[revInterApp intValue]] forKey:@"revision"];
    
    NSString *cont_inter = [SettingUtils get:CONTINUE_INTERVENTS user:[user.idutente stringValue]];
    if(cont_inter != nil){
        [diz3 setObject:cont_inter forKey:@"continue"];
    }
    
    NSString *json_req3 = [JsonCR2 createRequest:@"interventions" action:@"mysyncro" paramters:diz3 iduser:user.idutente];
    ASIFormDataRequest *request3 = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:[ComunicationsUtils getUrl]]];
    [request3 setDelegate:self];
    [request3 setPostValue:json_req3 forKey:@"DATA"];
    [request3 startAsynchronous];
}
-(void) refreshAll{
    myIntervents = [self.coreDataManager getInterventi];
    nominativo.text = [NSString stringWithFormat:@"%@ %@",user.nome,user.cognome];
    [table reloadData];
}



#pragma mark - Request
int s =0;
- (void)requestFinished:(ASIHTTPRequest *)request{
    //Leggo il risutato della richiesta
    NSDictionary *json = [JsonCR2 read:[request responseString]];
    NSString *response = [json objectForKey:@"response"];
    NSDictionary *req = [json objectForKey:@"request"];
    NSString *section = [req objectForKey:@"section"];
    NSString *action = [req objectForKey:@"action"];
    ////NSLog(@"%@",[request responseString]);
    NSLog(@"REQ_END: {section: %@, action: %@}",section,action);
    
    
    if([response isEqualToString:@"success"]){
        
        
        // Syncro Clients
        if([section isEqualToString:@"clients"] && [action isEqualToString:@"syncro"] ){
            NSDictionary *data = [json objectForKey:@"data"];
            NSString *revOnLine = [data objectForKey:@"revision"];
            NSString *revApp = (NSString*)[SettingUtils get:SAVE_REVISION_CLIENTS user:[user.idutente stringValue]];
            if(revApp == nil){ revApp = @"0";}
            if ([revOnLine intValue] > [revApp intValue]) {
                
                
                if([data objectForKey:@"continue"] == nil){
                    [SettingUtils set:SAVE_REVISION_CLIENTS obj:revOnLine user:[user.idutente stringValue]];
                    [SettingUtils del:CONTINUE_CLIENTS user:[user.idutente stringValue]];
                }else{
                    [SettingUtils set:CONTINUE_CLIENTS obj:[data objectForKey:@"continue"] user:[user.idutente stringValue]];
                    [self syncroClientAsync];
                }
                [self.coreDataManager syncroClienti:(NSArray *) [data objectForKey:@"mod"] del:(NSArray *) [data objectForKey:@"del"]];
            }
            s++;
        }
        
        
        // Syncro Users
        if([section isEqualToString:@"users"] && [action isEqualToString:@"syncro"] ){
            NSDictionary *data = [json objectForKey:@"data"];
            NSString *revOnLine = [data objectForKey:@"revision"];
            NSString *revApp = (NSString*)[SettingUtils get:SAVE_REVISION_USERS user:[user.idutente stringValue]];
            if(revApp == nil){ revApp = @"0";}
            if ([revOnLine intValue] > [revApp intValue]) {
                
                
                if([data objectForKey:@"continue"] == nil){
                    [SettingUtils set:SAVE_REVISION_USERS obj:revOnLine user:[user.idutente stringValue]];
                    [SettingUtils del:CONTINUE_USERS user:[user.idutente stringValue]];
                }else{
                    [SettingUtils set:CONTINUE_USERS obj:[data objectForKey:@"continue"] user:[user.idutente stringValue]];
                    [self syncroUserAsync];
                }
                
                
                [self.coreDataManager syncroUtenti:(NSArray *) [data objectForKey:@"mod"] del:(NSArray *) [data objectForKey:@"del"]];
            }
            s++;
        }
        
        
        // Syncro Intervents
        if([section isEqualToString:@"interventions"] && [action isEqualToString:@"mysyncro"] ){
            NSDictionary *data = [json objectForKey:@"data"];
            NSString *revOnLine = [data objectForKey:@"revision"];
            NSString *revApp = (NSString*)[SettingUtils get:SAVE_REVISION_INTERVENTS user:[user.idutente stringValue]];
            if(revApp == nil){ revApp = @"0";}
            if ([revOnLine intValue] > [revApp intValue]) {
                
                if([data objectForKey:@"continue"] == nil){
                    [SettingUtils set:SAVE_REVISION_INTERVENTS obj:revOnLine user:[user.idutente stringValue]];
                    [SettingUtils del:CONTINUE_INTERVENTS user:[user.idutente stringValue]];
                }else{
                    [SettingUtils set:CONTINUE_INTERVENTS obj:[data objectForKey:@"continue"] user:[user.idutente stringValue]];
                    s=2;
                    [self syncroIntervetsAsync];
                }
                
                
                [self.coreDataManager syncroInterventi:(NSArray *) [data objectForKey:@"mod"]
                                                   del:(NSArray *) [data objectForKey:@"del"]
                                                status:[data objectForKey:@"intervents"]];
                
            }
            
            NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
            long long t2 = [[NSNumber numberWithDouble: timeStamp] doubleValue] * 1000;
            
            //NSLog(@"TIME REQ : %lld ms", (t2-t1));
            
            
        }
        
        if(s==2){
            [self syncroIntervetsAsync];
            s++;
        }
        
        [self refreshAll];
    }else{
        
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request{
    NSError *error = [request error];
    //NSLog(@"%@",[error description]);
}




#pragma mark - tabella

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.myIntervents count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	return [NSString stringWithFormat: @"Interventi (%@ %@)",user.nome, user.cognome];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
    
    InterventoCD *intervento = [self.myIntervents objectAtIndex:indexPath.row];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    NSString *dateString = [dateFormatter stringFromDate:intervento.dataora];
    
    if([intervento.idintervento intValue]<0) cell.textLabel.text = @"Informazioni Nuovo";
    else cell.textLabel.text = [NSString stringWithFormat:@"Intervento %@",intervento.numero];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@",dateString,intervento.cliente.nominativo];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if([intervento.conflitto isEqual: @1]){
        [Util setCellAlert:cell];
    }else if([intervento.buffer isEqual: @1] || [intervento.idintervento intValue] < 0){
        [Util setCellModified:cell];
    }
    else{
        [Util setCellDefault:cell];
    }
    return cell;
}

// CellHeight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 50;
}

// CLICK
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    InterventoCD *inter = [self.myIntervents objectAtIndex:indexPath.row];
    
    OpenInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"OpenInterventoViewController"];
    open.intervento = inter;
    open.user = self.user;
    open.coreDataManager = self.coreDataManager;
    open.hashInter = [CoreDataManager hashcodeIntervento:inter];
    [self.navigationController pushViewController:open animated:TRUE];
    
}


@end
